namespace Brjnk.GpxExplorer.Workspace.Searching
{
    using System;
    using System.ComponentModel;
    using Brjnk.Common;
    using Brjnk.GpxExplorer.ViewModel;

    /// <summary>
    /// </summary>
    public class Pushpin : SearchPositionRequest
    {
        private string text;
        private IPoint point;
        private WeakEventListener listener;

        public Pushpin(GpsCoordinates coordinates, string text)
        {
            this.text = text;
            base.Position = coordinates;
        }

        public Pushpin(IPoint point)
        {
            this.point = point;
            if (point is INotifyPropertyChanged)
            {
                listener = new WeakEventListener(PositionChanged);
                PropertyChangedEventManager.AddListener((INotifyPropertyChanged)point, listener, "PositionI");
            }

            base.Position = point.PositionI;
        }

        public object ContentObject
        {
            get
            {
                if (point != null) return point; return this.text;
            }
        }

        private bool PositionChanged(Type managerType, object sender, EventArgs e)
        {
            base.Position = point.PositionI;
            return true;
        }

        public override Common.GpsCoordinates Position
        {
            get
            {
                return base.Position;
            }
            set
            {
                if (point != null) base.Position = value;
                else throw new InvalidOperationException("Position cannot be directly changed, because the position depends on IPoint.");
            }
        }

        protected override void GenerateStringRepresentation()
        {
            if (point == null) StringRepresentation = text;
            else if (point is INamed)
            {
                StringRepresentation = ((INamed)point).NameI;
            }
            else
            {
                StringRepresentation = point.ToString();
            }
        }
    }
}